package cn.yuanqiao.web.controller.archive.yuguidang;/**
 * @author 赵常飞
 * @date 2023/9/26 14:23
 */
                                    /****************
                                     * 翠微山居诗 其九 *
                                     *    宋  释冲邈  *
                                     * 朝见花开满树红, *
                                     * 暮观落叶又还空. *
                                     * 若将花比人间事, *
                                     * 花与人间事一同. *
                                     ****************/
import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.activiti.domain.ActivitiPackage;
import cn.yuanqiao.archive.appManager.service.ITenantCateMdataListService;
import cn.yuanqiao.archive.appManager.service.ITenantCategoryService;
import cn.yuanqiao.archive.common.util.SplitArchiveList;
import cn.yuanqiao.archive.wenjianzhengli.service.ILixianjieshouService;
import cn.yuanqiao.archive.wenjianzhengli.service.impl.WenjianzhengliServiceImpl;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.poi.ListToExclUtil;
import cn.yuanqiao.common.web.page.TableDataInfo;

import com.alibaba.fastjson2.JSONObject;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.yuguidang.domain.YuguidangArchiveForm;
import cn.yuanqiao.archive.yuguidang.service.IYuguidangService;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.web.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *
 *@AUTHOR:赵常飞
 *@date 2023/9/26 14:23
 */
@RestController
@RequestMapping("/archive/yuguidang")
public class yuguidangController extends BaseController {
    @Autowired
    private IYuguidangService yuguidangService;
    @Autowired
    private ITenantCategoryService iTenantCategoryService;
    @Autowired
    private WenjianzhengliServiceImpl wenjianzhengliService;
    @Autowired
    private ITenantCateMdataListService tenantCateMdataListService;
    @Autowired
    private RemoteActivitiService remoteActivitiService;
    @Autowired
    private SplitArchiveList splitArchiveList;
    @Autowired
    private ILixianjieshouService lixianjieshouService;
    @Autowired
    private ITenantCateMdataListService tenantMdataListService;
    @Log(title = "预归档申请单", businessType = BusinessType.INSERT)
    @PostMapping("/batchInsert")
    public AjaxResult batchInsertYqdaArchiveForm(@RequestBody List<YuguidangArchiveForm> yuguidangArchiveForms) throws ServiceException{
        String batchNo = String.valueOf(SnowflakeIdGenerator.generateId());
        StringBuilder ids = new StringBuilder();
        String userId = String.valueOf(SecurityUtils.getUserId());
        yuguidangArchiveForms.forEach(form -> {
            form.setFormId(String.valueOf(SnowflakeIdGenerator.generateId()));
            //form.setFormNo(batchNo);
            form.setTenantCode(SecurityUtils.getTenantCode());
            form.setUserId(userId);
            ids.append(form.getArchiveId()).append(",");
        });
        if (yuguidangService.checkArchiveIsAddForm(yuguidangArchiveForms)){
            return AjaxResult.error("已经添加到预归档审批单的数据不能再次添加");
        }
        if (yuguidangService.checkArchiveUserCategoryForm(yuguidangArchiveForms)){
            return AjaxResult.error("预归档审批单中已有其它门类的档案数据，请先提交再添加本门类数据");
        }

        YuguidangArchiveForm yuguidangArchiveForm = yuguidangArchiveForms.get(0);
        String subTableName = yuguidangArchiveForm.getSubTableName();
        String daType = yuguidangArchiveForm.getDaType();
        Long categoryId = yuguidangArchiveForm.getCategoryId();
        String idss = ids.toString();
        String msg = "";
        //检查卷内以及项目内是否有数据
        Map<String, List<String>> idWhichHasData = null;
        /*if("X".equals(daType) || "V".equals(daType)){
            idWhichHasData = yuguidangService.getIdWhichHasData(idss, daType, categoryId);
            if(idWhichHasData.size()==0){
                if("X".equals(daType)) msg += "项目中无案卷或案卷中无卷内件不能添加到申请单，";
                if("V".equals(daType)) msg += "案卷中无卷内件不能添加到申请单，";
            }else{
                Set<Map.Entry<String, List<String>>> entries = idWhichHasData.entrySet();
                Iterator<Map.Entry<String, List<String>>> iterator = entries.iterator();
                String tempStr = "";
                while(iterator.hasNext()){
                    Map.Entry<String, List<String>> next = iterator.next();
                    String key = next.getKey();
                    List<String> value = next.getValue();
                    if("X".equals(daType)){
                        for(int i=0;i<value.size();i++){
                            tempStr+=value.get(i)+",";
                        }
                    }
                    if("V".equals(daType)){
                        tempStr+=key+",";
                    }
                }
                idss = tempStr;
            }
            for(int i=0;i<yuguidangArchiveForms.size();i++){
                String archiveId = yuguidangArchiveForms.get(i).getArchiveId();
                if(!idWhichHasData.containsKey(archiveId)){
                    yuguidangArchiveForms.remove(i);
                    i--;
                }
            }
        }*/

        //检查是否生成档号
        if(yuguidangArchiveForms.size()!=0){
            if(idss.endsWith(",")) idss = idss.substring(0,idss.length()-1);
            if("X".equals(daType)){  //项目层校验卷。。。
                int size = yuguidangArchiveForms.size();
                TenantCategory tenantCategory = iTenantCategoryService.selectTenanCategoryByID(categoryId);
                Map<String, String> map = wenjianzhengliService.checkIsExistDh(String.valueOf(categoryId), "F".equals(daType) ? 0 : 1, tenantCategory.getFolderTableName(), idss);
                List<String> list = new ArrayList<>();  //需要除去的项目id集合
                if(idWhichHasData!=null){
                    Set<Map.Entry<String, List<String>>> entries = idWhichHasData.entrySet();
                    Iterator<Map.Entry<String, List<String>>> iterator = entries.iterator();
                    while (iterator.hasNext()){
                        Map.Entry<String, List<String>> next = iterator.next();
                        String key = next.getKey();   //项目id
                        List<String> value = next.getValue();  //项目内卷的id
                        Set<String> kset = map.keySet();    //没有档号的 案卷的id
                        value.stream().forEach(k->{
                            boolean contains = kset.contains(k);
                            if(!contains){
                                list.add(key);
                            }
                        });
                        /*Iterator<String> iterator1 = kset.iterator();
                        while (iterator1.hasNext()){
                            String next1 = iterator1.next();
                            if(value.contains(next1)){
                                list.add(key);
                            }
                        }*/
                    }
                }
                for(int i=0;i<yuguidangArchiveForms.size();i++){
                    String archiveId = yuguidangArchiveForms.get(i).getArchiveId();
                    if(list.contains(archiveId)){
                        yuguidangArchiveForms.remove(i);
                        i--;
                    }
                }
                if(size!=yuguidangArchiveForms.size()) msg += "已生成档号的不能添加到预归档申请单，";
            }else{
                int size = yuguidangArchiveForms.size();
                Map<String, String> map = wenjianzhengliService.checkIsExistDh(String.valueOf(categoryId), "F".equalsIgnoreCase(daType) ? 0 : 1, subTableName, idss);
                for(int i=0;i<yuguidangArchiveForms.size();i++){
                    String archiveId = yuguidangArchiveForms.get(i).getArchiveId();
                    if(!map.containsKey(archiveId)){
                        yuguidangArchiveForms.remove(i);
                        i--;
                    }
                }
                if(size!=yuguidangArchiveForms.size()) msg += "已生成档号的不能添加到预归档申请单，";
            }
        }


        int result = 0;
        if(yuguidangArchiveForms.size()!=0){
            result = yuguidangService.batchInsertYqdaArchiveForm(yuguidangArchiveForms);
            if (result>0){
                int i = yuguidangService.updateYqArchiveState(yuguidangArchiveForms,9);
            }
        }
        if(!"".equals(msg)) {
            if(msg.endsWith("，")) msg = msg.substring(0,msg.length()-1);
            return AjaxResult.error(msg);
        }else{
            return toAjax(result);
        }
    }
    @GetMapping(value = "/{formId}")
    public AjaxResult getInfo(@PathVariable("formId") Long formId)
    {
        return success(yuguidangService.selectYqdaArchiveFormByFormId(formId));
    }

    @PostMapping("/getArchiveInfo")
    public TableDataInfo getArchiveInfo(@RequestBody YuguidangArchiveForm yuguidangArchiveForm, @RequestParam("level") String level, @RequestParam("menuId")  String menuId) throws ArchiveException {
        //String commonColumns = yqdaArchiveFormService.getCommonColumns();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("categoryId",yuguidangArchiveForm.getCategoryId());
        jsonObject.put("level",level);
        jsonObject.put("menuId",menuId);
        List<Map<String, String>> getshowfield = tenantCateMdataListService.getshowfield(jsonObject);
        StringBuilder commonColumns = new StringBuilder();
        getshowfield.forEach(item -> commonColumns.append(item.get("FIELD_NAME")).append(","));
        startPage();
        List<Map<String,Object>> list = yuguidangService.getArchiveInfo(yuguidangArchiveForm,commonColumns.toString(),level);
        return getDataTable(list);
    }

    @Log(title = "预归档申请单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YuguidangArchiveForm yuguidangArchiveForm)
    {
        return toAjax(yuguidangService.updateYqdaArchiveForm(yuguidangArchiveForm));
    }

    @Log(title = "预归档申请单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{archiveIds}")
    public AjaxResult remove(@PathVariable String[] archiveIds)
    {
        List<YuguidangArchiveForm> yuguidangArchiveForm = yuguidangService.selectYqdaArchiveFormsByArchiveIds(archiveIds);
        yuguidangService.updateYqArchiveState(yuguidangArchiveForm,2);
        return toAjax(yuguidangService.deleteYqdaArchiveFormByArchiveIdsAndUserId(archiveIds,SecurityUtils.getUserId()));
    }
    @GetMapping("/getArchiveList")
    public AjaxResult getArchiveList(YuguidangArchiveForm yuguidangArchiveForm)
    {

        List<Map<String, Object>> list = yuguidangService.getArchiveListByArchiveCategory(yuguidangArchiveForm);
        return AjaxResult.success("查询成功",list);
    }

    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody YuguidangArchiveForm yuguidangArchiveForm)
    {

        String tenantCode = SecurityUtils.getTenantCode();
        YuguidangArchiveForm queryWarpper = new YuguidangArchiveForm();
        queryWarpper.setState("0");
        queryWarpper.setUserId(String.valueOf(SecurityUtils.getUserId()));
        String formNo = String.valueOf(SnowflakeIdGenerator.generateId());
        List<YuguidangArchiveForm> yuguidangArchiveForms = yuguidangService.selectYqdaArchiveFormList(queryWarpper);
        if (yuguidangArchiveForms.size()==0) return AjaxResult.error("预归档申请单中没有数据");
        List<Map<String,Object>> archiveList = yuguidangService.getArchiveListByArchiveFormList(yuguidangArchiveForms);
        R<String> formCode = remoteActivitiService.getFormCodeByBusinessKey("YArchive_Save",tenantCode);
        Map<String,Map<String, Object>> archiveListSplit = splitArchiveList.splitArchiveByFormCodeNew(formCode.getData(), archiveList);
        /*archiveListSplit = new ArrayList<>();
        Map<String, Object> testData1 = createTestData(1);
        archiveListSplit.add(testData1);

        Map<String, Object> testData2 = createTestData(2);
        archiveListSplit.add(testData2);*/
        yuguidangArchiveForm.setREMARK(yuguidangArchiveForm.getRemark());
        int size = archiveListSplit.size();
        int count = 0;
        List<String> taskIds = new ArrayList<>();
        for (Map.Entry<String, Map<String, Object>> entry:archiveListSplit.entrySet()) {
            Map<String, Object> varables = entry.getValue();
            if (entry.getKey().equals("notConditionValue")){
                count++;
                continue;
            }
            //remoteActivitiService.startProcessWsArchiveSave(varables);
            List<Map<String,Object>> archiveData = (List<Map<String,Object>>)varables.get("archiveData");
            if(archiveData == null){
                count++;
                continue;
            }
            StringBuilder archiveIds = new StringBuilder();
            archiveData.forEach(item->archiveIds.append(item.get("ID")).append(","));
            if ("".equals(archiveIds.toString())){
                count++;
                continue;
            }
            archiveIds.deleteCharAt(archiveIds.length()-1);
            System.out.println(varables.toString());
            varables.put("processVariables",yuguidangArchiveForm.toProcessMap());
            /*//TODO 测试用参数
            varables.put("archive_type","lt");
            varables.put("archive_has_mj","1");*/
            R<ActivitiPackage> activitiPackageR = remoteActivitiService.submitProcessWsYArchiveSave(varables);
            ActivitiPackage activitiPackage = activitiPackageR.getData();
            ProcessInstance processInstance = activitiPackage.getProcessInstance();
            String processInstanceId = processInstance.getId();
            String bussinessKey = activitiPackage.getBussinessKey();
            yuguidangArchiveForm.setArchiveId(archiveIds.toString());
            yuguidangArchiveForm.setWorkflowFormId(bussinessKey);
            yuguidangArchiveForm.setWorkflowId(processInstanceId);
            yuguidangArchiveForm.setState("5");
            yuguidangArchiveForm.setSplitNo(String.valueOf(SnowflakeIdGenerator.generateId()));
            yuguidangArchiveForm.setFormNo(formNo);
            int is = yuguidangService.batchUpdateByArchiveIds(yuguidangArchiveForm);
            R<String> taskIdByProcessId = remoteActivitiService.getTaskIdByProcessId(processInstanceId);
            if (taskIdByProcessId.getData()!=null){
                taskIds.add(taskIdByProcessId.getData());
            }

        }
        return AjaxResult.success("您的预归档申请单已经根据审批流程被分为"+(size-count)+"份申请提交",taskIds);
    }
    /**
     * 修改项目
     * @param object
     * @return
     */
    @Log(title = "修改项目", businessType = BusinessType.UPDATE)
   // @PreAuthorize("@ss.hasPermi('archive:ygd:updateItem')")
    @PostMapping("/updateItem")
    public AjaxResult updateItem(@RequestBody JSONObject object){
        logger.info(object.toJSONString());
        lixianjieshouService.updateItem(object);
        return AjaxResult.success();
    }

    /**
     * 修改组卷
     * @param object
     * @return
     */
    @Log(title = "修改组卷", businessType = BusinessType.UPDATE)
    //@PreAuthorize("@ss.hasPermi('archive:ygd:updateFolder')")
    @PostMapping("/updateFolder")
    public AjaxResult updateFolder(@RequestBody JSONObject object){
        logger.info(object.toJSONString());
        lixianjieshouService.updateFolder(object);
        return AjaxResult.success();
    }
    /**
     * 修改组件
     * @param object
     * @return
     */
    @Log(title = "修改组件", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('archive:lxjs:updateYqda')")
    @PostMapping("/updateYqda")
    public AjaxResult updateYqda(@RequestBody JSONObject object){
        logger.info(object.toJSONString());
        lixianjieshouService.updateYqda(object);
        return AjaxResult.success();
    }
    /**
     * 文件整理删除
     * @author syd
     * @param json
     * @return
     */
    @DeleteMapping("/delete")
    //@PreAuthorize("@ss.hasPermi('archive:ygd:delete')")
    @Log(title = "文件整理删除", businessType = BusinessType.DELETE)
    public AjaxResult delete(@RequestBody JSONObject json){
        String ids = json.getString("ids");
        if(!StringUtils.isNotEmpty(ids)){
            throw new ServiceException("ids不能为空");
        }
        return toAjax(wenjianzhengliService.delete(json));
    }

    /**
     * 文件整理导出
     * @author syd
     * @param response
     * @param
     */
    @PostMapping("/export")
    @Log(title = "文件整理导出", businessType = BusinessType.EXPORT)
    //@PreAuthorize("@ss.hasPermi('archive:ygd:export')")
    public void export(HttpServletResponse response, @RequestParam("data1") String data1)
    {
        JSONObject json = JSONObject.parseObject(data1);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        Workbook wb = null;
        try {
            //获取表头以及数据
            String categoryId = json.getString("categoryId");
            String menuId = json.getString("menuId");
            Integer finalType = Integer.valueOf(json.getString("type"));
            List<Map<String, String>> getexportfield = tenantMdataListService.getexportfield(Long.valueOf(categoryId), Long.valueOf(menuId), finalType);
            Map<String, Object> map = wenjianzhengliService.getExportTitleAndBody(json,getexportfield);
            wb = ListToExclUtil.getWorkbookByList((List<String>)map.get("title"),(List<List<String>>)map.get("body"),"sheet",(Map<String, Map<String,String>>)map.get("dict"));
            wb.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(wb!=null){
                IOUtils.closeQuietly(wb);
            }
        }
    }
    /**
     * 排案卷号和件号
     * @param json
     * @return
     */
    @PutMapping("/pieceNumber")
    //@PreAuthorize("@ss.hasPermi('archive:ygd:pieceNumber')")
    @Log(title = "排案卷号/件号", businessType = BusinessType.UPDATE)
    public AjaxResult pieceNumber(@RequestBody JSONObject json){
        int i = wenjianzhengliService.pieceNumber(json);
        if(i==-1){
            throw new ServiceException("案卷中档号为空的不能排卷内档号");
        }
        if(i==-2){
            throw new ServiceException("件号重复不能生成档号");
        }
        if(i==-3){
            throw new ServiceException("档号不符合规则");
        }
        if(i==-4){
            throw new ServiceException("卷内件生成档号末位超出补零位数，请修改档号规则");
        }
        if(i==-5){
            throw new ServiceException("生成档号末位超出补零位数，请修改档号规则");
        }
        if(i==-6){
            throw new ServiceException("档号组成字段为空的不能生成档号");
        }
        return toAjax(i);
    }

    /**
     * 清除案卷号、件号
     * @author syd
     */
    @PutMapping("/clearNumber")
    //@PreAuthorize("@ss.hasPermi('archive:ygd:clearNumber')")
    @Log(title = "清除案卷号/件号", businessType = BusinessType.UPDATE)
    public AjaxResult clearNumber(@RequestBody JSONObject json){
        int i = wenjianzhengliService.clearNumber(json);
        if(i==-1){
            throw new ServiceException("所选数据未生成档号");
        }
        return toAjax(i);
    }

    /**
     * 获取档号规则著录项最后一节
     * @author syd
     * @param json
     * @return
     */
    @PostMapping("/getLastZlx")
    //@PreAuthorize("@ss.hasPermi('archive:ygd:insertPieceNumber')")
    public AjaxResult getLastZlx(@RequestBody JSONObject json){
        Map<String, Object> lastZlx = wenjianzhengliService.getLastZlx(json);
        return success(lastZlx);
    }

    /**
     * 手动排档号
     *
     * @param json
     * @return
     */
    @PutMapping("/insertPieceNumber")
    //@PreAuthorize("@ss.hasPermi('archive:ygd:insertPieceNumber')")
    @Log(title = "手动排档号", businessType = BusinessType.UPDATE)
    public AjaxResult insertPieceNumber(@RequestBody JSONObject json) {
        int i = wenjianzhengliService.insertPieceNumber(json);
        if (i == -1) {
            throw new ServiceException("档号组成字段为空的不能生成档号");
        }
        return toAjax(i);
    }
    /**
     * 排卷内件档号
     * @param json
     * @return
     */
    @PostMapping("/pieceInnerNumber")
    //@PreAuthorize("@ss.hasPermi('archive:ygd:pieceInnerNumber')")
    @Log(title = "排卷内件档号", businessType = BusinessType.UPDATE)
    public AjaxResult pieceInnerNumber(@RequestBody JSONObject json){
        return toAjax(wenjianzhengliService.pieceInnerNumber(json));
    }
    /**
     * 合并卷
     * @param object
     * @return
     */
    @Log(title = "合并卷", businessType = BusinessType.UPDATE)
    //@PreAuthorize("@ss.hasPermi('archive:ygd:assemblyFolder')")
    @PostMapping("/assemblyFolder")
    public AjaxResult assemblyFolder(@RequestBody JSONObject object){
        logger.info(object.toJSONString());
        //yuguidangService
        object.put("fromygd","true");
        lixianjieshouService.assemblyFolder(object);
        return AjaxResult.success();
    }

    @Log(title = "退回", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('archive:ygd:tuihui')")
    @PostMapping("/tuihui")
    public AjaxResult tuihui(@RequestBody JSONObject object){
        return toAjax(yuguidangService.tuihui(object));
    }
}
